package com.wanjia.estate.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.wanjia.estate.pojo.document.InvoiceInfo;
import com.wanjia.estate.template.IntegerRedisTemplate;
import com.wanjia.estate.template.InvoiceInfoRedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    @Autowired
    public InvoiceInfoRedisTemplate invoiceInfoRedisTemplate(RedisConnectionFactory factory) {
        InvoiceInfoRedisTemplate template = new InvoiceInfoRedisTemplate();
        config(template, factory, InvoiceInfo.class);
        return template;
    }

    @Bean
    @Autowired
    public IntegerRedisTemplate integerRedisTemplate(RedisConnectionFactory factory) {
        IntegerRedisTemplate template = new IntegerRedisTemplate();
        config(template, factory, Integer.class);
        return template;
    }

    private static <T> void config(RedisTemplate<?, ?> template, RedisConnectionFactory factory, Class<T> t) {
        // 设置连接
        template.setConnectionFactory(factory);

        // 设置序列化
        FastJsonRedisSerializer<T> serializer = new FastJsonRedisSerializer<>(t);
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);

        // 刷新设置
        template.afterPropertiesSet();
    }
}
